// withLatestFrom 实例
// 拖拽案例
import {
  fromEvent,
  withLatestFrom,
  takeUntil,
  switchMap,
  // 节流
  throttleTime,
  // 防抖
  debounceTime,
  from,
} from "rxjs";
// 拖拽元素
const draggableElement = document.getElementById("draggable");
// 加事件 鼠标按下
const mouseDown$ = fromEvent(draggableElement, "mousedown");
// 加事件 鼠标移动
const mouseMove$ = fromEvent(draggableElement, "mousemove").pipe(
  throttleTime(30)
);
// 加事件 鼠标松开
const mouseUp$ = fromEvent(draggableElement, "mouseup");

mouseDown$
  .pipe(
    switchMap(() =>
      mouseMove$.pipe(takeUntil(mouseUp$.pipe(debounceTime(500))))
    ),
    withLatestFrom(mouseDown$, (moveEvent, downEvent) => {
      return {
        left: moveEvent.clientX - downEvent.offsetX,
        top: moveEvent.clientY - downEvent.offsetY,
      };
    })
  )
  .subscribe(({ left, top }) => {
    draggableElement.style.left = left + "px";
    draggableElement.style.top = top + "px";
  });
mouseDown$.unsubscribe();
mouseMove$.unsubscribe();
mouseUp$.unsubscribe();
/**
 * switchMap上已经消费了一次 mouseDown，转化成 mouseMove，
 * 为啥下面的 withLatestFrom 还能拿到 mouseDonw
 */
